package com.dianrui.qiyouriding.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.MyApplication;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.bean.ChangeName;
import com.dianrui.qiyouriding.event.RreshMy;
import com.dianrui.qiyouriding.util.BitmapUtils;
import com.dianrui.qiyouriding.util.ConvertUtils;
import com.dianrui.qiyouriding.util.GlideUtil;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.NoDoubleClickUtils;
import com.dianrui.qiyouriding.util.SharedUtil;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * 个人信息
 */
public class PersonInfoActivity extends BaseActivity {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.pic)
    ImageView pic;
    @BindView(R.id.show_mobile)
    TextView showMobile;
    @BindView(R.id.show_names)
    TextView showNames;
    @BindView(R.id.show_auth)
    TextView showAuth;


    @Override
    public int getContentViewId() {
        return R.layout.person_info;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(true, R.color.main_color);
        checkWirtePerssions();
        title.setText(getResources().getString(R.string.personinfo_title));
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("mobile")) && SPUtils.getInstance().getString("mobile").length() > 6) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < SPUtils.getInstance().getString("mobile").length(); i++) {
                char c = SPUtils.getInstance().getString("mobile").charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
            showMobile.setText(sb.toString());
        }
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("nickname"))) {
            showNames.setText(SPUtils.getInstance().getString("nickname"));
        }

        if (StringUtils.isEmpty(SPUtils.getInstance().getString("card"))) {
            showAuth.setText(getString(R.string.not_certified));
            showAuth.setTextColor(ContextCompat.getColor(PersonInfoActivity.this, R.color.red));
        } else {
            showAuth.setText(getString(R.string.certified));
            showAuth.setTextColor(ContextCompat.getColor(PersonInfoActivity.this, R.color.black));
        }


    }

    @Override
    public void initData() {
    }


    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void checkWirtePerssions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);

        }
    }

    public void getUserInfo() {
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
            OkHttpRequest.getInstance().postRequests(Url.USERINFO, jsonObject.toString(), new OkHttpRequest.XCallBack() {

                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("face"))) {
                                        GlideUtil.loadUserImageViewSize(getApplicationContext(), jsonObject.optJSONObject("data").optString("face"), pic);
                                    }
                                    if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("mobile")) && jsonObject.optJSONObject("data").optString("mobile").length() > 6) {
                                        StringBuilder sb = new StringBuilder();
                                        for (int i = 0; i < jsonObject.optJSONObject("data").optString("mobile").length(); i++) {
                                            char c = jsonObject.optJSONObject("data").optString("mobile").charAt(i);
                                            if (i >= 3 && i <= 6) {
                                                sb.append('*');
                                            } else {
                                                sb.append(c);
                                            }
                                        }
                                        showMobile.setText(sb.toString());
                                    }
                                    SPUtils.getInstance().put("is_partner", jsonObject.optJSONObject("data").optString("is_partner"));//is_partner
                                    showNames.setText(jsonObject.optJSONObject("data").optString("nickname"));
                                    if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("card"))) {
                                        showAuth.setText(getString(R.string.not_certified));
                                        showAuth.setTextColor(ContextCompat.getColor(PersonInfoActivity.this, R.color.red));
                                    } else {
                                        showAuth.setText(getString(R.string.certified));
                                        showAuth.setTextColor(ContextCompat.getColor(PersonInfoActivity.this, R.color.black));
                                    }
                                    SPUtils.getInstance().put("member_token", jsonObject.optJSONObject("data").optString("member_token"),true);

                                }else  if (Constant.BACKLOGIN.equals(jsonObject.optString("status"))) {
                                    SPUtils.getInstance().clear();
                                    JumpKillActivitys(LoginActivity.class);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        }
    }


    @OnClick({R.id.back, R.id.click_pic, R.id.click_nickname, R.id.click_mobile, R.id.click_auth})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.click_pic:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(PersonInfoActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        choosePicUserImage();
                    } else {
                        ActivityCompat.requestPermissions(PersonInfoActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    choosePicUserImage();
                }
                break;

            case R.id.click_nickname:
                Intent changeNameintent = new Intent(PersonInfoActivity.this, ChangNameActivity.class);
                Bundle changeNamebundle = new Bundle();
                changeNamebundle.putString("nickname", showNames.getText().toString());
                changeNameintent.putExtras(changeNamebundle);
                startActivity(changeNameintent);
                break;

            case R.id.click_mobile:
                JumpActivitys(ShowMobileActivity.class);
                break;
            case R.id.click_auth:
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("card"))) {
                    Intent intent = new Intent(PersonInfoActivity.this, AuthActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("isBackAuth", "1");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    JumpActivitys(AuthInfoActivity.class);
                }
                break;

            default:
                break;
        }

    }

    //选择拍照或者相册选图
    private void choosePicUserImage() {
        MyUtil.createPhotoChooseDialog(0, 1, PersonInfoActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
            @Override
            public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                if (resultList == null && resultList.size() == 0) {
                    ToastUtil.showToast("照片未选中");
                    return;
                }
                GlideUtil.loadUserImageViewSize(getApplicationContext(), resultList.get(0).getPhotoPath(), pic);
                setInfoFace(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight())));
            }

            @Override
            public void onHanlderFailure(int requestCode, String errorMsg) {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)//修改昵称后更新本地并上传给后台
    public void onMessageEvent(ChangeName changeName) {
        showNames.setText(changeName.name);
        setInfoName(changeName.name);
    }


    private void setInfoFace(String value) {
        showLoadingDialog("正在上传头像中...");
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("face", value);
        OkHttpRequest.getInstance().postRequests(Url.SETINFO, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SPUtils.getInstance().put("face", jsonObject.optJSONObject("data").optString("face"),true);
                                GlideUtil.loadUserImageViewSize(getApplicationContext(), jsonObject.optJSONObject("data").optString("face"), pic);

                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void setInfoName(String value) {
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("nickname", value);
        OkHttpRequest.getInstance().postRequests(Url.SETINFO, jsonObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SPUtils.getInstance().put("member_id", jsonObject.optJSONObject("data").optString("member_id"));
                                SPUtils.getInstance().put("nickname", jsonObject.optJSONObject("data").optString("nickname"),true);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    choosePicUserImage();
                }
                break;

            default:
                break;

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().post(new RreshMy());
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
